#include "qtlrcwidget.h"

#include <QFile>
#include <QPainter>

#include <QDebug>

QtLrcWidget::QtLrcWidget(QWidget *parent) : QWidget(parent)
{
    m_strLrcText = "歌词加载失败~~";
    m_currPos = 1;
}

void QtLrcWidget::loadLrcFile(const QString &fileName)
{
    m_mapLrc.clear();
    QString p = "\\[([0-9]+:[0-9]+.[0-9]+)\\]";
    QFile file(fileName);
    if (file.open(QFile::ReadOnly))
    {
        QTextStream text_stream(&file);
        while(!text_stream.atEnd())
        {
            QString content = text_stream.readLine(0);
            QString pattern(p);
            QRegExp rx(pattern);

            QString strGeci = content.right(content.size() - (content.lastIndexOf("]")+1));
            while (content.indexOf(rx)>=0)
            {
                if (rx.matchedLength() > 1)
                {
                    QString strTime = rx.capturedTexts().at(1);

                    int nMin = strTime.mid(0, 2).toInt();
                    int nSec = strTime.mid(3, 2).toInt();
                    int nSSec = strTime.mid(6, 2).toInt();

                    qint64 nPos =  (nMin * 60 + nSec) * 100 + nSSec;
                    m_mapLrc.insert(nPos, strGeci);
                }

                content = content.mid(10);
            }
        }
        m_strLrcText = m_mapLrc.first();
        file.close();
        this->update();
    } else {
        qDebug() << "open lrc file failed!~" << fileName;
    }
}

void QtLrcWidget::postionChanged(qint64 position)
{
    QString strCurLrc = "";
    position /= 10;
    foreach (const qint64 &nPos, m_mapLrc.keys())
    {
        if (nPos > position) {
            break;
        }

        strCurLrc = m_mapLrc.value(nPos);
    }

    if (strCurLrc != m_strLrcText)
    {
        m_strLrcText = strCurLrc;
        this->update();
    }
}

void QtLrcWidget::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    int ntxtW = painter.fontMetrics().horizontalAdvance(m_strLrcText);
    QRect txtRect = this->rect();
    painter.setPen("#9954ffc8");
    painter.drawLine(txtRect.topLeft(), txtRect.topRight());

#if 0
    painter.setPen(Qt::white);
    painter.drawText(txtRect, Qt::AlignLeft | Qt::AlignBottom, m_strLrcText);

    // 绘制未播放图层
    painter.setPen("#f0f0f0");
    painter.drawText(txtRect, Qt::AlignLeft | Qt::AlignBottom, m_strLrcText);
#endif
    // 绘制已播放图层
    if (m_currPos > 0) {
        painter.setPen("#54ffc8");
        painter.drawText(QRect(txtRect.left(), txtRect.top(), ntxtW * m_currPos, txtRect.height()), Qt::AlignLeft | Qt::AlignBottom, m_strLrcText);
    }
}
